package org.progin.cloudfolder;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//SQL database handler
public class DB {
	//Attributes
	private Connection m_Connection;
	
	//Constructor
	public DB() { }
	
	public DB(String url, String username, String password) {
		try {
			//Load driver 
    		Class.forName("com.mysql.jdbc.Driver");
    		
    		//Create connection
			m_Connection = DriverManager.getConnection(url,username, password);
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public ResultSet executeQuery(String query) {
		//Initialize result
		ResultSet m_Result = null;
		Statement m_Statement = null;
		
		try {
			//Create statement and execute
			m_Statement = m_Connection.createStatement();
			m_Result = m_Statement.executeQuery(query);
			
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		
		//Return result set, not closing statement because result set is still active
		return m_Result;
	}
	
	public int executeUpdate(String query) {
		//Initialize result
		int m_Result = 0;
		Statement m_Statement = null;
		
		try {
			//Create statement and execute
			m_Statement = m_Connection.createStatement();
			m_Result = m_Statement.executeUpdate(query);
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//Close statement
			if (m_Statement!=null) {
				try {
					m_Statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return m_Result;
	}
	
	public void Dispose() {
		try {
			//Close connection
			m_Connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
